package idiolect.webstorage;

import idiolect.core.IOUtil;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.concurrent.Callable;

public class TopicDownloadTask implements Callable<File> {
    private final TopicInfo info;
    private static final String MARKER = "<td class=\"source\">";

    public TopicDownloadTask(TopicInfo info) {
        this.info = info;
    }

    public File call() throws Exception {
        byte[] content = IOUtil.getContent(new URL("http://code.google.com/p/idiolect/source/browse/trunk/rc/Dictionaries/" + info.name));
        String s = new String(content, "utf-8");
        int pos1;
        int pos2 = 0;
        File f = new File(IOUtil.FOLDER, info.name.endsWith(".dict") ? info.name : (info.name + ".dict"));
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(f);
            do {
                pos1 = s.indexOf(MARKER, pos2);
                if (pos1 == -1)
                    break;
                pos2 = s.indexOf('<', pos1 + MARKER.length());
                if (pos2 == -1)
                    break;
                pw.println(new String(s.substring(pos1 + MARKER.length(), pos2).getBytes("Windows-1252")).replaceAll("&quot;", "\""));
            } while (true);
            pw.flush();
            return f;
        } catch (IOException ioe) {
            ioe.printStackTrace();
            return null;
        } finally {
            IOUtil.close(pw);
        }
    }
}
